<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/header.jsp" %>

<!-- page specific plugin scripts -->
    <script type="text/javascript" src="${ctx}/assets/js/ztree/js/jquery.ztree.core-3.5.js"></script> 
    <script type="text/javascript">
    var jsonArray = $.parseJSON('${jsonArray}');
    var checkType = '${checkType}';
    var zTree, rMenu;
    var setting = {
    		data: {
    			simpleData: {
    				enable: true
    			}
    		},
    		edit:{
    			enable: true,
    			showRemoveBtn: false,
    			showRenameBtn: false
    		},
    		view: {
    			dblClickExpand: false
    		},
    		check: {
    			enable: true
    		},
    		callback: {
    			onRightClick: OnRightClick,
    			onClick: onClick
    		},
    		async: {
    			enable: true,
    			url:"${ctx}/org/haveChildNodes",
    			autoParam:["id","messageType","checkType"],
    			type: "post",
    			dataType: "json",
    			dataFilter: filter
    		}
    	};
    
    function filter(treeId, parentNode, childNodes) {
    	if(childNodes.length < 1) {
    		zTree.removeChildNodes(parentNode);
    	} else {
    		return resultToNodes(childNodes);
    	}
    }
  //兼容火狐版本，增加全局变量window.event
    if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){  
    	var $E = function(){var c=$E.caller; while(c.caller)c=c.caller; return c.arguments[0]};
        __defineGetter__("event", $E);
    }
  //鼠标左键点击查看所选子节点的详细信息
    function onClick(event, treeId, treeNode, clickFlag) {
    	var param;
    	var url = "";
    		if(treeNode.messageType=="org") {
    			param={"orgId":treeNode.id};
    			url = "${ctx}/org/orgDetail";
    		} else if(treeNode.messageType=="dept"){
    			param={"deptId":treeNode.id};
    		    url = "${ctx}/org/deptDetail";
    		}
    		$("#deptDetailForm").show();
    		$("#deptDetailForm").load(url,param);
    }


    //鼠标右键点击显示新增子节点菜单
    function OnRightClick(event, treeId, treeNode) {
    	if(treeNode == null){
    		return null;
    	}
    	var position = vControl('GETMOUSEPOSINPIC',$("#body_menu").get(0));
    	if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
    		zTree.cancelSelectedNode();
    		showRMenu(treeNode,  position.lnt, position.lat);
    	} else if (treeNode && !treeNode.noR) {
    		var scrollTop1 = $("#body_menu").find("div").first().scrollTop();
    		var scrollTop2 = document.documentElement.scrollTop || $("body").scrollTop();
    		//alert("scrollTop2:"+scrollTop2);
    		zTree.selectNode(treeNode);
    		var _scrollTop1 = $("#body_menu").find("div").first().scrollTop();
    		var _scrollTop2 = document.documentElement.scrollTop || $("body").scrollTop();
    			//document.documentElement.scrollTop || $("body").scrollTop();
    			//alert("_scrollTop2:"+_scrollTop2);
    		//排除360急速模式与IE11版本中出现滚动条跳动问题
    		//实现方法：记录跳动之前的滚动条位置，判断跳动之后，滚动条位置是否发生了改变，如果发生改变了，则还原回来
    		if(scrollTop1 != _scrollTop1 || scrollTop2 != _scrollTop2){
    			$("#body_menu").find("div").first().scrollTop(scrollTop1);
    			document.documentElement.scrollTop = scrollTop2;
    			$("body").scrollTop(scrollTop2);
    		}
    		//alert(document.documentElement.scrollTop);
    		if(isFirefox=navigator.userAgent.indexOf("Firefox")>0)
    			showRMenu(treeNode, position.lnt, position.lat);
    		//document.documentElement.scrollTop = scrollTop2;
    		//$("body").scrollTop(scrollTop2);
    		//alert(document.documentElement.scrollTop);
    		//$("#body_menu").find("div").first().scrollTop(scrollTop1);
    		//之所以Y轴需要加上document.documentElement.scrollTop，是因为只有IE的情况下，需要计算并加上滚动条位置，而其他如火狐，谷歌则不需要
    		//而火狐，或者谷歌中的document.documentElement.scrollTop计算出来的值为0
    		else showRMenu(treeNode, position.lnt, position.lat + document.documentElement.scrollTop);
    	 }
    }
    //显示菜单
    function showRMenu(node, x, y) {
        $("#rMenu ul").show();
        if (node.messageType=="dept") {
            $("#addOrg").hide();
            $("#addDept").show();
        } else {
            $("#addOrg").show();
            $("#addDept").show();
        }
        rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
      
        $("body").bind("mousedown", onBodyMouseDown);
        
       
    }
    function hideRMenu() {
    	if (rMenu) rMenu.css({"visibility": "hidden"});
    	$("body").unbind("mousedown", onBodyMouseDown);
    }
    function onBodyMouseDown(event){
    	if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
    		rMenu.css({"visibility" : "hidden"});
    	}
    }

     var orgO = "${ctx}/assets/js/ztree/css/zTreeStyle/img/diy/org.png", 
         orgC = "${ctx}/assets/js/ztree/css/zTreeStyle/img/diy/org.png", 
         org = "${ctx}/assets/js/ztree/css/zTreeStyle/img/diy/org.png", 
         dept = "${ctx}/assets/js/ztree/css/zTreeStyle/img/diy/dept.png";
     
          //检查节点状态，如果为非启用状态，则不允许添加子节点
            function checkStatus(zNodes) {
            	var z = zNodes==null?zTree.getSelectedNodes()[0]:zNodes;
            	if(z.status != "1") {
            		alert("该" + (z.messageType=="org"?"机构":"部门") + "为非启用或停用状态,不能增加" + (z.checkType=="user"?"人员":"子部门") + "!");
            		return false;
            	}
            	return true;
            }
         
          //分割子节点
            function resultToNodes(result){
              	var fNodes = [];
             		$.each(result,function(i,node){
             			fNodes.push(getNodes(node,checkType));
             		});
              	return fNodes;
            }
            //设置子节点信息
              function getNodes(node,checkType){
              	var fNode = {
              		id:node.id, //节点编号
              		pId:node.pId, //父节点编号
              		name:node.text,//节点名称（在机构树上展示的名称）
              		open:node.isOpen==1?true:false, //是否打开子节点
              		messageType:node.nodeType, //节点属性（自定义），分org/dept
              		status:node.status, //状态，0-未启用 1-启用 2-停用
              		isParent:node.hasChild==1?true:false,//是否含有子节点
              		type:node.type,//机构节点专用类型 1-机构 0-部门
              		checkType:checkType, //机构树类型 分org(只展示机构)/dept(展示机构、部门)/user(展示机构、部门、人员)
              		iconOpen:orgO, //节点图标
              		iconClose:orgC,//节点图标
              		icon:org // 节点图标
              	};
              	if(node.type == "item") {
              		fNode.iconOpen = dept;
              		fNode.iconClose = dept;
              		fNode.icon = dept; 
              	} 
              	return fNode;
              }
            //新增机构/部门子节点
            function addZNode(str){
            	var zNodes =zTree.getSelectedNodes()[0];
            	if(!checkStatus()) return;	
            	$("#deptDetailForm").show();
            	var param = "";
            	if(str.id =="btn_org"){
            		param={"pId":zNodes.id};
            		$("#deptDetailForm").load("${ctx}/org/toAddOrg",param);
            	}
            	if(str.id =="btn_dept"){
            		param = {"pId":zNodes.id,"nodeType":zNodes.messageType};
            		$("#deptDetailForm").load("${ctx}/org/toAddDept",param);
            	}
            	rMenu.css({"visibility" : "hidden"});
            	
            }
            
    var scripts = [null, null];
    $('.page-content-area').ace_ajax('loadScripts', scripts, function() {
    	     //页面加载树结构
        $.fn.zTree.init($("#orgTree"), setting, resultToNodes(jsonArray));
        zTree = $.fn.zTree.getZTreeObj("orgTree");
        rMenu = $("#rMenu");
       //debugger;
        var params ={"orgId":'${rootOrgId}'};
        $("#deptDetailForm").load("${ctx}/org/orgDetail",params);  
    });
    //计算鼠标点击位置
    var JPos = {};
   (function($){
	$.$getAbsPos = function(p){
		var _x = 0;
		var _y = 0;
		while(p.offsetParent){
				_x += p.offsetLeft;
				_y += p.offsetTop;
				p = p.offsetParent;
		}
		
		_x += p.offsetLeft;
		_y += p.offsetTop;
		
		return {x:_x,y:_y};
	};
	
	$.$getMousePos = function(evt){
		
		var _x,_y;
      evt = evt || window.event;
		if(evt.pageX || evt.pageY){
			_x = evt.pageX;
			_y = evt.pageY;
		}else if(evt.clientX || evt.clientY){
			_x = evt.clientX + document.body.scrollLeft - document.body.clientLeft;
			_y = evt.clientY + document.body.scrollTop - document.body.clientTop;
		}else{
			return $.$getAbsPos(evt.target);	
		}
		return {x:_x,y:_y};
	}
})(JPos);

function vControl(pChoice){
	switch(pChoice){
		case "GETMOUSEPOSINPIC":
			var mPos = JPos.$getMousePos();
			var iPos = JPos.$getAbsPos(arguments[1]);
			
			window.status = (mPos.x - iPos.x) + " " + (mPos.y - iPos.y);
			var rightclickPoint = {lnt:(mPos.x - iPos.x + 5),lat:(mPos.y - iPos.y + 40)};
			return rightclickPoint;
			break;
	}

}
</script>
  
 <!--   <style type="text/css">
        .ztree li span.button.switch.level0 {visibility:hidden; width:1px;}
        .ztree li ul.level0 {padding:0; background:none;}
    </style> -->
    <style type="text/css">
        div#rMenu {
        position:absolute; 
        visibility:hidden; 
        top:0; 
        background-color: #fff;
        text-align: center;
        padding: 1px;
        }
        div#rMenu ul li{
            margin: 1px 0;
            padding: 0 5px;
            cursor: pointer;
            list-style: none outside none;
            background-color: #fff;
        } 
    </style>  

		<!-- #section:plugins/fuelux.treeview -->
		<div class="row">
			<div class="col-sm-12">
				<div class="widget-box widget-color-blue2">				
					<div class="widget-header">
						<h4 class="widget-title lighter smaller">
						<hw:orgName orgId="${rootOrgId}"/>(${rootOrgId})
						</h4>
						<!-- #section:custom/widget-box.toolbar -->
						<div class="widget-toolbar">
							<a href="#" data-action="fullscreen" class="orange2"><i class="ace-icon fa fa-expand"></i></a>
							<a href="#" data-action="close"><i class="ace-icon fa fa-times"></i></a>
						</div> 
						<!-- /section:custom/widget-box.toolbar -->
					</div> 
					<div id="body_menu" >
						<div  style="height:700px;overflow:auto;">
							<ul id="orgTree" class="ztree"></ul>
						</div>
						<div id ="rMenu" style="position:absolute;">
					  	<ul class="dropdown-menu" role="menu">
					         <li id="btn_org" onclick="addZNode(this);"><a tabindex="-1" class="grey" id="addOrg"><i class='ace-icon fa fa-university blue'></i> 新增子机构</a></li>
					         <!--
					         	<li id="btn_dept" onclick="addZNode(this);"><a tabindex="-1" class="grey" id="addDept"><i class='ace-icon fa fa-sitemap green'></i> 新增子部门</a></li>
					         -->
					  	</ul>
					    </div>
                   </div>
      </div>
			</div>
		</div>



